import React, { useState, useEffect } from 'react';
import { Pagination, Spin } from 'antd';
import { useNavigate } from 'react-router-dom';
import Card from '@/components/blog';
import { getAllRecommendBlog } from '@/api/index';
import { getAllBlogs } from '@/api/blog';
import css from './index.module.less';


export default function Index() {
	const item = sessionStorage.getItem('info')
	const info = JSON.parse(item);
  const [blogs, setBlogs] = useState([]);
	const [spinning, setSpinning] = useState(true);
  useEffect(() => {}, [info])
  useEffect(() => {
  	if (info == null) {
			getAllRecommendBlog(current, size).then((res) => {
				setSpinning(true);
				if (res.code === 200) {
					setBlogs(res.data.blogDtos);
					setTotal(res.data.total);
					setSpinning(false);
				}
			});
		} else {
  		const id = info.id;
  		getAllBlogs(current, size, id).then((res) => {
				setSpinning(true);
				if (res.code === 200) {
					setBlogs(res.data.blogDtos);
					setTotal(res.data.total);
					setSpinning(false);
				}
			})
		}
  }, []);
  const navigate = useNavigate();
  const toDetail = (data) => {
		navigate(`/blogDetail/${data.blog.id}`);
	}
	const [current, setCurrent] = useState(1);
  const [size, setSize] = useState(3);
  const [total, setTotal] = useState(5);

	const onChange = (page, size) => {
		if (info == null) {
			getAllRecommendBlog(page, size).then((res) => {
				setSpinning(true);
				if (res.code === 200) {
					setBlogs(res.data.blogDtos);
					setTotal(res.data.total);
					setSpinning(false);
				}
			});
		} else {
			const id = info.id;
			getAllBlogs(page, size, id).then((res) => {
				setSpinning(true);
				if (res.code === 200) {
					setBlogs(res.data.blogDtos);
					setTotal(res.data.total);
					setSpinning(false);
				}
			})
		}
		setCurrent(page);
	};
	const onShowSizeChange = (cCurrent, cSize) => {
		if (info == null) {
			getAllRecommendBlog(cCurrent, cSize).then((res) => {
				setSpinning(true);
				if (res.code === 200) {
					setBlogs(res.data.blogDtos);
					setTotal(res.data.total);
					setSpinning(false);
				}
			});
		} else {
			const id = info.id;
			getAllBlogs(cCurrent, cSize, id).then((res) => {
				setSpinning(true);
				if (res.code === 200) {
					setBlogs(res.data.blogDtos);
					setTotal(res.data.total);
					setSpinning(false);
				}
			})
		}
		setSize(cSize);
	}
  return (
    <div className={css.content}>
			<Spin tip='Loading...' spinning={spinning} className={css.spinning} />
				{blogs.length === 0? <></> : blogs.map((blog, index) => {
					return (
						<div style={{marginBottom: "20px"}} key={index} onClick={() => toDetail(blog)}>
							<Card data={blog} />
						</div>
					);
				})}
				<Pagination style={{marginBottom: '10px'}}
					current={current} onChange={onChange}
					onShowSizeChange={onShowSizeChange}
					defaultPageSize={3}
					pageSizeOptions={[3, 6, 12]}
					total={total}
				/>
      </div>
  );
}
